package com.zd.controller;

import com.zd.entity.News;
import com.zd.entity.Topic;
import com.zd.service.NewsService;
import com.zd.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/news/")
public class NewsController {
    @Autowired
    private NewsService newsService;
    @Autowired
    private TopicService topicService;

    @GetMapping("list")
    public String newsList(Model model,Integer pageNo){
        if(pageNo == null){
            pageNo=1;
        }
        Page page = newsService.queryJpaPageNews(pageNo);
        model.addAttribute("page",page);
        return "admin/admin";
    }

    @GetMapping("toadd")
    public String toAdd(Model model){
        List<Topic> topics=topicService.queryAllTopics();
        model.addAttribute("topics",topics);
        return "admin/news_add";
    }

    @PostMapping("doadd")
    public String doAdd(News news){
        News news1 = newsService.addNews(news);
        return "redirect:/news/list";
    }

    @GetMapping("toupdate")
    public String toUpdate(Long nid,Model model){
        News news = newsService.queryNewsByNid(nid);
        List<Topic> topics=topicService.queryAllTopics();
        model.addAttribute("news",news);
        model.addAttribute("topics",topics);
        return "admin/news_modify";
    }

    @PostMapping("doupdate")
    public String doUpdate(News news){
        newsService.updateNews(news);
        return "redirect:/news/list";
    }

    @GetMapping("delete")
    public String delete(Long nid){
        newsService.deleteNewsById(nid);
        return "redirect:/news/list";
    }
}
